package com.xusiyan08.controller;

import com.xusiyan08.config.JwtUtil;
import com.xusiyan08.dto.AuthResponse;
import com.xusiyan08.entity.User;
import com.xusiyan08.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User loginRequest) {
        User user = userService.login(loginRequest.getStudentId(), loginRequest.getPassword());
        if (user != null) {
            String token = jwtUtil.generateToken(user.getUserId(), user.getStudentId(), user.getUserRole().name());
            return ResponseEntity.ok(new AuthResponse(token, user));
        }
        return ResponseEntity.badRequest().body("登录失败");
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            User savedUser = userService.register(user);
            return ResponseEntity.ok(savedUser);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("注册失败：" + e.getMessage());
        }
    }

    @GetMapping("/{userId}")
    public ResponseEntity<?> getUserById(@PathVariable Long userId) {
        User user = userService.getUserById(userId);
        if (user != null) {
            return ResponseEntity.ok(user);
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/{studentId}")
    public ResponseEntity<?> getUserByStudentId(@PathVariable String studentId) {
        try {
            User user = userService.getUserByStudentId(studentId);
            if (user != null) {
                return ResponseEntity.ok(user);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("查询学生信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("查询失败：" + e.getMessage());
        }
    }




    @PutMapping("/{userId}")
    public ResponseEntity<?> updateUser(
            @PathVariable Long userId,
            @RequestBody User user,
            @RequestHeader(value = "X-Current-User-Id", required = false) Long currentUserId) { // Get current user ID from header

        // *** Permission Check: Only the authenticated user can update their own profile ***
        if (currentUserId == null || !currentUserId.equals(userId)) {
            // Log a warning for security monitoring
            logger.warn("User {} attempted to update user profile {} without permission.", currentUserId, userId);
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("您无权修改此用户信息。"); // 403 Forbidden
        }
        // **********************************************************************************

        user.setUserId(userId); // Ensure the user ID from the path is used
        User updatedUser = userService.updateUser(user);
        return ResponseEntity.ok(updatedUser);
    }

    // TODO: Replace this placeholder method with your actual logic to get the authenticated user's ID
    // This method needs to securely retrieve the ID of the currently logged-in user
    private Long getCurrentAuthenticatedUserId() {
        // Returning a dummy ID for compilation purposes. REPLACE THIS IN PRODUCTION!
        logger.warn("Using placeholder/insecure method to get current user ID. REPLACE THIS IN PRODUCTION!");
        return 1L; // Dummy user ID - REPLACE WITH SECURE AUTHENTICATED USER ID
    }
}